import app from 'flarum/forum/app';
import { extend, override } from 'flarum/common/extend';
import SettingsPage from 'flarum/forum/components/SettingsPage';
import Button from 'flarum/common/components/Button';
import Model from 'flarum/common/Model';
import User from 'flarum/common/models/User';
import WelcomeHero from 'flarum/forum/components/WelcomeHero';
import AuthMobileModal from './components/AuthMobileModal';
import EditMobileModal from './components/EditMobileModal';
import ChangePasswordModal from './components/ChangePasswordModal';
import SignUpModal from 'flarum/forum/components/SignUpModal';
import LogInModal from 'flarum/forum/components/LogInModal';
import ForgetFormModal from './components/ForgetFormModal'

import Stream from "flarum/common/utils/Stream";
import CaptchaModal from "./components/CaptchaModal";


app.initializers.add('wanecho/mobilelogin', () => {
  User.prototype.mobile = Model.attribute('mobile')
  extend(SettingsPage.prototype, 'accountItems', function (items) {
    const mobile = app.session.user.mobile();
    if (mobile != null) {
      items.add('echo-bindmobile', Button.component({
        className: "Button",
        onclick() {
          app.modal.show(EditMobileModal);
        }
      }, '修改手机号'))
      items.add(
        'changePassword', Button.component({
          className: "Button",
          onclick() {
            app.modal.show(ChangePasswordModal);
          }
        }, '更改密码'))
    } else {
      items.add('echo-bindmobile', Button.component({
        className: "Button",
        onclick() {
          app.modal.show(AuthMobileModal);
        }
      }, '绑定手机'))
    }

  });

  //绑定提示
  override(WelcomeHero.prototype, 'view', function (original) {
    if (app.session.user && app.session.user.isEmailConfirmed()) {
      if (app.session.user.data.attributes.mobile != null) {
        return original();
      }
      return m("div.Alert", [
        m("div.container", [
          m("span.alert-danger", "检测到你还未绑定手机号，请先绑定手机。绑定手机号码后才可发帖和留言。"),
          m("a.bind[href='/settings']", '立即绑定')
        ])
      ]);
    }
    return original();
  });


  //手机注册
  extend(SignUpModal.prototype, "oninit", function () {
    this.mobile = Stream("");
    this.msgcode = Stream("");
    this.captcha = Stream("");
    this.captcha_url = '/captcha?' + Math.random()
    this.msgcode_text = "获取验证码"
    this.issendcode = false
  });
  extend(SignUpModal.prototype, 'fields', function (items) {
    //手机号
    items.add(
      "WanechoMobile",
      m(".Form-group", [
        m("input.FormControl", {
          name: "mobile",
          type: "text",
          placeholder: '手机号',
          bidi: this.mobile,
          disabled: this.loading,
        }),
      ]),
      30
    )
    items.add(
      'captcha',
      m(".Form-group", m('.auth-line', [
        m("input.FormControl", {
          name: "captcha",
          type: "text",
          placeholder: '图形验证码',
          bidi: this.captcha,
          onchange: () => {
            console.log(3343);
          }
        }),
        m("img.captcha_img", {
          src: this.captcha_url,
          width: "120",
          onclick: () => {
            this.captcha_url = '/captcha?' + Math.random()
            m.redraw();
          }
        })
      ])),
      30
    )
    items.add(
      'msgcode',
      m(".Form-group", m('.auth-line', [
        m("input.FormControl", {
          name: "msgcode",
          type: "text",
          placeholder: '验证码',
          bidi: this.msgcode,
          disabled: this.loading,
        }),
        m("button.Button Button--primary", {
          onclick: () => {
            if (this.issendcode) {
              return;
            }
            if (this.captcha() == '') {
              app.alerts.show({ type: 'error' }, "请填写图形验证码！");
              return;
            }
            if (this.mobile() == '') {
              app.alerts.show({ type: 'error' }, "请填写手机号！");
              return;
            }
            this.issendcode = true
            app.request({
              method: 'POST',
              url: app.forum.attribute('apiUrl') + '/regsendcode',
              body: {
                mobile: this.mobile(),
                captcha: this.captcha(),
              },
            })
              .then(() => {
                app.alerts.show({ type: 'success' }, "短信发送成功");
                this.msgcode_text = "已发送"
                m.redraw();
              })
              .catch(() => {

                this.issendcode = false
              })
              .then(this.loaded.bind(this));

          },
          type: "button"
        }, this.msgcode_text)
      ])),
      30
    )


  });
  extend(SignUpModal.prototype, "submitData", function (data) {
    data.mobile = this.mobile;
    data.msgcode = this.msgcode;
    return data;
  });
  override(LogInModal.prototype, 'forgotPassword', function () {

    app.modal.show(ForgetFormModal);
  })

});
